﻿using System.Windows.Media.Imaging;
using System;
using System.Windows.Data;
using System.IO;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Media;
using System.Data.Linq;

namespace BizControl.Presentation.Infrastructure.Converters
{
  public class ImageConverter : IValueConverter
  {
    public ImageSource DefaultImageSource { get; set; }

    #region IValueConverter Members

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      BitmapImage defaultImage, image;
      if (value != null)
      {
        var valueAsBinary = value as Binary;
        image = new BitmapImage();
        if (null != valueAsBinary)
        {
          var valueAsBytes = valueAsBinary.ToArray();
          using (MemoryStream reader = new MemoryStream(valueAsBytes))
          {
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.StreamSource = reader;
            image.EndInit();
          }
        }
        return image;
      }
      else
      {
        if (DefaultImageSource != null)
        {
          var uri = new Uri(DefaultImageSource.ToString());
          defaultImage = new BitmapImage(uri);
          return defaultImage;
        }
        return null;
      }
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
      return null;
    }

    #endregion
  }
}
